//
//  FZLBSService
//  LBSDemo
//
//  Created by yanming.huym on 14-4-25.
//  Copyright (c) 2014年 yanming.huym. All rights reserved.
//

#import "SRLocationBaseSService.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface SRLocationBaseSService () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, copy) FZLocation2DBlock latitudeLongtitudeBlock;
@property (nonatomic, copy) FZCountryBlock countryBlock;
@property (nonatomic, copy) FZCountryCityBlock cityBlock;
@property (nonatomic, copy) FZLBSBlock llfailure;          //获取经纬度时出现错误的处理
@property (nonatomic, copy) FZLBSBlock locationFailure;    //获取国家地区时出现错误的处理
@property (nonatomic) BOOL hasAlreadyReceivedCoordinates;

@end

@implementation SRLocationBaseSService

//========================APIs============================

- (BOOL)canGetLocation {
    if ([CLLocationManager locationServicesEnabled] && kCLAuthorizationStatusAuthorized == [CLLocationManager authorizationStatus]) {
        return YES;
    }
    return NO;
}

- (void)latitudeAndLongtitude:(FZLocation2DBlock )finishBlock failure:(FZLBSBlock)failure {
    self.latitudeLongtitudeBlock = finishBlock;
    self.llfailure = failure;
    [self initLocationManager];
}


- (void)appleCountry:(FZCountryBlock)finishBlock failure:(FZLBSBlock)failure {
    self.countryBlock = finishBlock;
    self.llfailure = failure;
    self.locationFailure = failure;
    [self initLocationManager];
}

- (void)appleCountryCity:(FZCountryCityBlock)finishBlock failure:(FZLBSBlock)failure {
    self.cityBlock = finishBlock;
    self.llfailure = failure;
    self.locationFailure = failure;
    [self initLocationManager];
}
+ (NSString *)localeCountryCode {
    NSLocale *locale = [NSLocale currentLocale];
    return [locale objectForKey:NSLocaleCountryCode];
}

//=========================================================


- (void)initLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
        self.hasAlreadyReceivedCoordinates = NO;
        if (kCLAuthorizationStatusDenied == [CLLocationManager authorizationStatus]) {
            if (self.permissionDenyBlock) {
                self.permissionDenyBlock();
            }
        }
    }
    else {
        if (self.disableBlock) {
            self.disableBlock();
        }
        if (self.llfailure) {
            self.llfailure();
        }
    }
}

#pragma mark - Location Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    [manager stopUpdatingLocation];
    
    if (self.hasAlreadyReceivedCoordinates) {
        return;
    }
    
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D position = location.coordinate;
    if (self.latitudeLongtitudeBlock) {
        self.latitudeLongtitudeBlock(position.latitude,position.longitude);
    }
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) {
            if (self.locationFailure) {
                self.locationFailure();
                return;
            }
        }
        CLPlacemark *placemark = [placemarks lastObject];
        if (placemark) {
            if (self.countryBlock) {
                self.countryBlock(placemark.ISOcountryCode);
            }
            if (self.cityBlock) {
                self.cityBlock(placemark.ISOcountryCode,placemark.locality);
            }
        }
        else {
            if (self.cityBlock) {
                self.countryBlock(@"");
            }
            if (self.cityBlock) {
                self.cityBlock(@"",@"");
            }
        }
    }];
    
    self.hasAlreadyReceivedCoordinates = YES;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [manager stopUpdatingLocation];
    if (self.hasAlreadyReceivedCoordinates) {
        return;
    }
    if (self.llfailure) {
        self.llfailure();
    }
    self.hasAlreadyReceivedCoordinates = YES;
}

@end
